C++ is a bunch of small
additions to C, and one major addition. This one addition is the
object-oriented approach. As its name suggests, this deals with objects. Of
course, these are not real-life objects. Instead, these objects are the
essential definitions of real world objects. Structures are one step away
from these objects, they do not possess one element of them: functions. The
definitions of these objects are called classes. The easiest way to think
about a class is to imagine a structure that has functions. What is this mysterious structure (not the programming type)? Well, it is not only a collection of variables under one heading, but it is a collection of functions under that same heading. If the structure is a house, then the functions will be the doors and the variables will be the items inside the house. They usually will be the only way to modify the variables in this structure, and they are usually the only to access the variables in this structure. The idea to make programs more modular. A section of code will have its own functions and variables that control what it can do, and it does not require anything outside of itself to function. While the class may require initialization with data, it does not require outside variables or functions to manipulate the data. That allows programs to reuse the same code more easily. From now on, we shall call these structures with functions classes (I guess Marx would not like C++). The syntax for these classes is simple. First, you put the keyword 'class' then the name of the class. Our example will use the name computer. Then you put an open bracket. Before putting down the different variables, it is necessary to put the degree of restriction on the variable. There are three levels of restriction. The first is public, the second protected, and the third private. For now, all you need to know is that the public restriction allows any part of the program, including that which is not part of the class, access the variables specified as public. The protected restriction prevents functions outside the class to access the variable. The syntax for that is merely the restriction keyword (public, private, protected) and then a colon. Finally, you put the different variables and functions (You usually will only put the function prototype[s]) you want to be part of the class. Then you put a closing bracket and semicolon. Keep in mind that you still must end the function prototype(s) with a semi-colon. |